package com.justgame.project.cloud.base.config;

import com.justgame.project.cloud.base.entity.StringEncrypt;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.sql.*;

@Component
@MappedJdbcTypes({JdbcType.VARCHAR})  //对应数据库类型
@MappedTypes({StringEncrypt.class})   //java数据类型
public class StringEncryptTypeHandlerHandler implements TypeHandler<StringEncrypt> {

    @Override
    public void setParameter(PreparedStatement ps, int i, StringEncrypt parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setNull(i, Types.VARCHAR);
        } else {
            ps.setString(i, parameter.getEncryptedValue());
        }
    }

    @Override
    public StringEncrypt getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return value == null ? null : StringEncrypt.encryptedOf(value);
    }

    @Override
    public StringEncrypt getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return value == null ? null : StringEncrypt.encryptedOf(value);
    }

    @Override
    public StringEncrypt getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return value == null ? null : StringEncrypt.encryptedOf(value);
    }
}
